<?php
/**
 * 解析fba收支明细报表-数据入库
 * User: bgl
 * Date: 2023/11/10
 * Time: 18:08
 */

namespace App\Logic\Amazon\Api\Parse;


use App\Models\Amazon\AmazonSkuName;
use App\Models\Amazon\LedgerDetailView;

class GetLedgerDetailViewData{

    public static function exe($lines,$accountId){

        if(!$accountId)return 2;
        if(!is_array($lines))return 2;
        $i = 0;
        $count = 0;
        try{
            foreach($lines as $line){
                $flag = self::_addFbaFulfillment($line,$accountId);
                $flag && $count++;
                $i++;
            }
        }catch (\Exception $e){
            report($e);
        }
        return $i == $count ? 1 : 2;
    }

    /**
     * @param $line
     * @param $accountId
     * @return bool
     */
    private static function _addFbaFulfillment($line,$accountId){

        //AmazonSkuName::addName($line['MSKU'],$line['Title']);

        $receivedDate = gmdate('Y-m-d H:i:s',strtotime($line['Date']));
        $item = [
            'date' => $receivedDate,
            'account_id' => $accountId,
            'fnsku' => $line['FNSKU'],
            'seller_sku' => $line['MSKU'],
            'title' => $line['Title'],
            'event_type' => $line['Event Type'], //报表类型
            'fba_shipment_id' => $line['Reference ID'], //"eventType":"Receipts" (发运单号)
            'quantity' => $line['Quantity'], //数量
            'fulfillment_center_id' => $line['Fulfillment Center'], //发运中心标识
            'disposition' => $line['Disposition'], //处置方式
            'reason' => $line['Reason'], //原因
            'country' => $line['Country'], //国家
            'reconciled_quantity' => $line['Reconciled Quantity'], //调整数量
            'unreconciled_quantity' => $line['Unreconciled Quantity'], //未调整数量
            'date_and_time' => $line['Date and Time'], //日期和时间
        ];

        //$count = LedgerDetailView::query()
        //    ->where('date',$receivedDate)
        //    ->where('seller_sku',$line['MSKU'])
        //    ->where('quantity',$line['Quantity'])
        //    ->where('account_id',$accountId)
        //    ->where('fulfillment_center_id',$line['Fulfillment Center'])
        //    ->where('event_type',$line['Event Type'])
        //    ->count();
        //if($count > 0)return true;

        $re = LedgerDetailView::query()->create($item);
        return !$re ? false : true;
    }

}
